// user vuex
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_USERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  SET_STATE(state) {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // 登入 得到token
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    console.log(username, password)
    return new Promise((resolve, reject) => {
      login({ username, password }).then(res => {
        commit('SET_TOKEN', res.data.token)
        setToken(res.data.token)
        resolve()
      }).catch(err => {
        reject(err)
      })
    })
  },

  // 获得用户信息
  async getUserInfo({ commit }) {
    const result = await getUserInfo()
    // console.log(result)
    if (result.code === 200) {
      commit('SET_USERINFO', result.data)
      return Promise.resolve()
    } else {
      return Promise.reject(result.msg)
    }
  },

  // 退出
  resetToken({ commit }) {
    removeToken()
    resetRouter()
    commit('SET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
